package com.example.mywanandroid.ui.nav.mine;


import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.fragment.NavHostFragment;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.example.mywanandroid.R;
import com.example.mywanandroid.base.BaseFragment;
import com.example.mywanandroid.config.Constants;
import com.example.mywanandroid.databinding.FragmentMineBinding;
import com.example.mywanandroid.service.LocationService;
import com.example.mywanandroid.ui.activity.main.MainViewModel;
import com.example.mywanandroid.util.ImageSelectUtil;
import com.example.mywanandroid.util.ToastUtils;
import com.guoxiaoxing.phoenix.core.model.MediaEntity;
import com.guoxiaoxing.phoenix.picker.Phoenix;

import java.util.Objects;

import static android.app.Activity.RESULT_OK;

public class MineFragment extends BaseFragment<FragmentMineBinding, MainViewModel> {
    private static final String TAG = "MineFragment";
    private LocationService locationService;
    private Location location;

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initViewModel() {
        mViewModel = new ViewModelProvider(getActivity()).get(MainViewModel.class);
    }

    @Override
    protected void bindViewModel() {
        mDataBinding.setViewModel(mViewModel);
        mDataBinding.setMineFragment(this);
    }

    @Override
    protected void init() {
        mViewModel.loadMyIntegral();
        initLocationService();
        initData();
    }

    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            locationService = ((LocationService.LocalBinder) service).getService();
            Log.d(TAG, "onServiceConnected: ");
            if (locationService != null) {
                locationService.getLocation(new AMapLocationListener() {
                    @Override
                    public void onLocationChanged(AMapLocation curLocation) {
                        Log.d(TAG, "onLocationChanged: " + curLocation.getLatitude() + "");
                        location = curLocation;
                    }
                });
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.d(TAG, "onServiceDisconnected: ");
            locationService = null;
        }
    };

    private void initLocationService() {
        Intent intent = new Intent(getActivity(), LocationService.class);
        getActivity().bindService(intent,conn,Context.BIND_AUTO_CREATE);
//        getActivity().startService(intent);
    }

    private void initData() {
        mViewModel.getUserBean().observe(this, bean -> {
            if (bean != null) {
                mDataBinding.tvUserName.setText(bean.getNickname());
            } else {
                Toast.makeText(getActivity(), "退出成功", Toast.LENGTH_SHORT).show();
                mDataBinding.tvUserName.setText(getResources().getString(R.string.no_login));
                mDataBinding.tvUserIntegral.setText("");
            }
        });
        if (location != null) {
            Log.d(TAG, "initData: " + location.getLatitude() + "");
        }
    }

    public void selectImage() {
        ImageSelectUtil.selectPictureWithFragment(this, Constants.RequestCode.SELECT_PICTURE);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (locationService != null) {
            getActivity().unbindService(conn);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == Constants.RequestCode.SELECT_PICTURE) {
                if (Phoenix.result(data) == null) {
                    Toast.makeText(getContext(), "图片选择失败", Toast.LENGTH_SHORT).show();
                    return;
                }

                MediaEntity mediaEntity = Phoenix.result(data).get(0);
                mViewModel.updateUserHeader(mediaEntity.getFinalPath());
            }
        }
    }


    /**
     * 跳转到待办清单界面
     */
    public void startTodFragment() {
        NavHostFragment.findNavController(MineFragment.this).navigate(R.id.toDoFragment);
    }

    /**
     * 跳转到我的收藏界面
     */
    public void startCollectFragment() {
        NavHostFragment.findNavController(MineFragment.this).navigate(R.id.nav_collect);
    }

    /**
     * 跳转到我的分享界面
     */
    public void startShareFragment() {
        Bundle bundle = new Bundle();
        bundle.putInt(Constants.ParamCode.PARAM1, mViewModel.getUserBean().getValue().getId());
        bundle.putString(Constants.ParamCode.PARAM2, mViewModel.getUserHeader().getValue());
        NavHostFragment.findNavController(MineFragment.this).navigate(R.id.nav_share, bundle);
    }

    /**
     * 跳转到积分详情页面
     */
    public void startIntegralFragment() {
        NavHostFragment.findNavController(MineFragment.this).navigate(R.id.coinListFragment);
    }

    /**
     * 跳转积分排行榜
     */
    public void startCoinRankFragment() {
        NavHostFragment.findNavController(MineFragment.this).navigate(R.id.coinRankListFragment);
    }

    /**
     * 跳转设置界面
     */
    public void startSettingFragment() {
        ToastUtils.showToast(getContext(), "功能正在开发中");
    }
}
